package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.AddFamilyDto;
import com.zzyl.nursing.dto.DeviceDataReportDTO;
import com.zzyl.nursing.dto.UserLoginDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-22
 */
@Slf4j
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IDeviceDataService deviceDataService;

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private IElderService elderService;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private List<String> nickNameList = Arrays.asList("好柿开花", "大吉大利", "今晚吃鸡", "三羊开泰");


    /**
     * 微信小程序登录接口
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginDto dto) {
        //1. 获取微信唯一身份标识openId
        String openId = wechatService.getOpenId(dto.getCode());

        //2. 根据openId查询用户
        FamilyMember member = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();

        //3. 如果用户不存在则新增用户（自动注册）
        if (member == null) {
            Collections.shuffle(nickNameList);//打乱集合中元素的顺序

            //生成随机昵称
            String nickName = nickNameList.get(0) + RandomStringUtils.randomNumeric(4);

            member = FamilyMember.builder()
                    .openId(openId) //唯一标识
                    .name(nickName)//昵称
                    .build();
            this.save(member);
        }

        //4. 如果手机号不存在则获取微信绑定的手机号
        if (StrUtil.isBlank(member.getPhone())) {
            String phoneNum = wechatService.getPhoneNum(dto.getPhoneCode());

            //5. 更新手机号到用户表
//            FamilyMember memberUpdate = FamilyMember.builder()
//                    .id(member.getId()) //更新条件
//                    .phone(phoneNum)//更新字段对应的值
//                    .build();
//            this.updateById(memberUpdate);

            if (StrUtil.isNotBlank(phoneNum)) {
                this.lambdaUpdate()
                        .eq(FamilyMember::getId, member.getId()) //更新条件
                        .set(FamilyMember::getPhone, phoneNum)//更新字段对应的值
                        .update();
            }
        }

        //6. 基于userId和昵称生成Token令牌
        String token = tokenService.createToken(
                Map.of(
                        "userId", member.getId(),
                        "nickName", member.getName()
                ));

        //7. 封装响应结果对象
        return LoginVo.builder().nickName(member.getName()).token(token).build();
    }


    /**
     * 实战需求：绑定家人
     *
     * @param dto
     */
    @Override
    public void addFamily(AddFamilyDto dto) {
        //根据老人身份证号查询老人信息
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getIdCard())
                .eq(Elder::getName, dto.getName())
                .one();

        //老人信息判空
        if (ObjUtil.isEmpty(elder)) {
            throw new BaseException("老人信息不存在！");
        }

        //从线程变量中获取家属id
        Long familyMemberId = UserThreadLocal.get();

        //构建老人家属关系表对象
        FamilyMemberElder familyMemberElder = FamilyMemberElder.builder()
                .elderId(elder.getId())
                .familyMemberId(familyMemberId)
                .remark(dto.getRemark())
                .createBy(Integer.valueOf(familyMemberId.toString()))
                .build();

        familyMemberElderMapper.insert(familyMemberElder);
    }

    /**
     * 实战需求：获取老人列表
     *
     * @return
     */
    @Override
    public List<ElderVO> getElderList() {
        //获取家属id
        Long familyMemberId = UserThreadLocal.get();

        //获取家属绑定的老人列表
        List<FamilyMemberElder> myElderList = familyMemberElderMapper.selectList(Wrappers.<FamilyMemberElder>lambdaQuery()
                .eq(FamilyMemberElder::getFamilyMemberId, familyMemberId)
        );
        //判空
        if (CollUtil.isEmpty(myElderList)) {
            return Collections.EMPTY_LIST;
        }

        //封装vo实体集合并返回
        List<ElderVO> result = myElderList.stream().map(memberElder -> {
            Elder elder = elderService.getById(memberElder.getElderId());
            return ElderVO.builder()
                    .id(memberElder.getId())
                    .familyMemberId(familyMemberId)
                    .elderId(memberElder.getElderId())
                    .elderName(elder.getName())
                    .build();
        }).collect(Collectors.toList());

        return result;

    }

    /**
     * 实战需求：分页查询老人列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<PageMemberElderVo> pageElderList(Integer pageNum, Integer pageSize) {
        //获取家属id
        Long familyMemberId = UserThreadLocal.get();
        PageHelper.startPage(pageNum, pageSize);
        return familyMemberElderMapper.pageElderList(familyMemberId);
    }

    /**
     * 实战需求：获取家人设备健康数据
     *
     * @param device
     * @return
     */
    @Override
    public AjaxResult getHealthInfo(Device device) {
        if (StrUtil.isBlank(device.getDeviceName() )||  StrUtil.isBlank(device.getProductKey()) ){
            throw new BaseException("老人未绑定智能设备！");
        }

        //获取设备相关数据
        Device elderDevice = deviceService.lambdaQuery()
                .eq(Device::getDeviceName, device.getDeviceName())
                .eq(Device::getProductKey, device.getProductKey())
                .one();

        //从Redis中获取设备的最新数值并进行格式转换
        String deviceDataStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_DATA_LATEST, elderDevice.getIotId());
        List<DeviceData> deviceDataList = JSONUtil.toList(deviceDataStr, DeviceData.class);

        //封装健康数据集合并返回

//        List<HealthInfo> propertyStatusInfo = deviceDataList.stream().map(deviceData -> {
//            HealthInfo healthInfo = HealthInfo.builder()
//                    .identifier(deviceData.getFunctionId())
//                    .time(String.valueOf(DateUtil.parse(deviceData.getAlarmTime().toString()).getTime()))
//                    .value(deviceData.getDataValue())
//                    .build();
//        }).collect(Collectors.toList());
        List<HealthInfo> propertyStatusInfo = new ArrayList<>();
        List<HealthInfo> heartRate = new ArrayList<>();
        deviceDataList.forEach(deviceData -> {
            HealthInfo healthInfo = HealthInfo.builder()
                    .identifier(deviceData.getFunctionId())
                    .time(String.valueOf(DateUtil.parse(deviceData.getAlarmTime().toString()).getTime()))
                    .value(deviceData.getDataValue())
                    .build();
            if ("HeartRate".equals(healthInfo.getIdentifier())) {
                heartRate.add(healthInfo);
            } else {
                propertyStatusInfo.add(healthInfo);
            }
        });
        propertyStatusInfo.add(3,heartRate.get(0));

        HealthInfoVO list = HealthInfoVO.builder().propertyStatusInfo(propertyStatusInfo).build();

        Map<String, Object> result = new HashMap<>();
        result.put("list", list);

        return AjaxResult.success(result);
    }

    /**
     * 实战需求：解绑老人
     * @param id
     * @return
     */
    @Override
    public void deleteById(Integer id) {
        familyMemberElderMapper.deleteById(id);
    }

    /**
     *  实战需求：统计当天每小时设备指定属性的平均值
     * @param dto
     * @return
     */
    @Override
    public List<DeviceDataDayAVGVO> queryDeviceDataListByDay(DeviceDataReportDTO dto) {

        //首先将前端传过来的毫米级时间戳转换为LocalDateTime对象，方便调用方法和时间比对
        //开始时间
        LocalDateTime startDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(dto.getStartTime()), ZoneId.of("Asia/Shanghai"));
        //结束时间
        LocalDateTime endDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(dto.getEndTime()), ZoneId.of("Asia/Shanghai"));


        //创建时间划分节点midTime，由startTime+59分59秒时得来
        LocalDateTime midTime = startDateTime.plusMinutes(59).plusSeconds(59);

        //创建结果集合
        List<DeviceDataDayAVGVO> list = new ArrayList<>();
        //复用型结果对象，不用每次都去new，节省资源
        DeviceDataDayAVGVO baseVO = null;

        //while循环，直到时间划分节点midTime = 24:00:00 > endTime = 23:59:59停止
        while (midTime.isBefore(endDateTime)){
            log.info("当前开始时间段：{}  当前截止时间段：{}",startDateTime,midTime);
            //获取从startTime到midTime时间段内的数据平均值，由于midTime由startTime+59分59秒得来，因此每次时间间隔都是1小时
            Double hourAvg = deviceDataMapper.getTimeAvg(startDateTime, midTime, dto.getFunctionId(), dto.getIotId());
            //如果后端返回为空，则代表该时间段内无数据，手动置0
            if(hourAvg == null){
                hourAvg = 0d;
            }
            //构造结果对象，封装了startTime的toLocalTime，也就是小时分钟秒以及对应的数据
            baseVO = DeviceDataDayAVGVO.builder().dateTime(startDateTime.toLocalTime().toString()).dataValue((double)(int)(double)hourAvg).build();
            //添加结果对象
            list.add(baseVO);
            //将startTime+1小时，从下一个小时开始继续遍历
            startDateTime = startDateTime.plusHours(1);
            //将midTime+1小时，保证永远比startTime多59分59秒的情况下才能正确的划分时间
            midTime =  startDateTime.plusMinutes(59).plusSeconds(59);
        }

        return  list;
    }

    /**
     * 实战需求：统计每周每日设备指定属性的平均值
     * @param dto
     * @return
     */
    @Override
    public List<DeviceDataDayAVGVO> queryDeviceDataListByWeek(DeviceDataReportDTO dto) {
        //首先将前端传过来的毫米级时间戳转换为LocalDateTime对象，方便调用方法和时间比对
        LocalDateTime startDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(dto.getStartTime()), ZoneId.of("Asia/Shanghai"));
        LocalDateTime endDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(dto.getEndTime()), ZoneId.of("Asia/Shanghai"));

        //创建时间划分节点midTime，由startTime+23小时59分钟得来
        LocalDateTime midTime = startDateTime.plusHours(23).plusMinutes(59);

        //创建结果集合
        List<DeviceDataDayAVGVO> list = new ArrayList<>();
        //复用型结果对象，不用每次都去new，节省资源
        DeviceDataDayAVGVO baseVO = null;


        while (midTime.isBefore(endDateTime)){
            log.info("当前开始日期：{}  当前截止日期：{}",startDateTime,midTime);
            Double dayAvg = deviceDataMapper.getTimeAvg(startDateTime, midTime, dto.getFunctionId(), dto.getIotId());
            if(dayAvg == null){
                dayAvg = 0d;
            }
            baseVO = DeviceDataDayAVGVO.builder().dateTime(startDateTime.toLocalDate().getMonthValue()+"."+startDateTime.getDayOfMonth()).dataValue((double)(int)(double)dayAvg).build();
            list.add(baseVO);
            //将startTime+1天，从下一个小时开始继续遍历
            startDateTime = startDateTime.plusDays(1);
            //将midTime+1天，保证永远比startTime多23小时59分钟的情况下才能正确的划分时间
            midTime =  startDateTime.plusHours(23).plusMinutes(59);
        }

        return  list;
    }


}
